/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> v;
        TreeNode* prev = nullptr;
        if (root == nullptr)
        {
            return v;
        }
        stack<TreeNode*> t;
        TreeNode* cur = root;
        while (cur || !t.empty())
        {
            while (cur)
            {
                t.push(cur);
                cur = cur->left;
            }
            TreeNode* ttop = t.top();
            if (ttop->right == nullptr || ttop->right == prev)
            {
                prev = ttop;
                v.push_back(ttop->val);
                t.pop();

            }
            else
            {
                cur = ttop->right;
            }
        }
        return v;
    }
};